package NewChatRoom;

import java.sql.*;

//连接数据库存储账号信息
public class AccountDAO {
    public AccountDAO(){
        try {
            Class.forName("com.mysql.jdbc.Driver");
        }catch (ClassNotFoundException e){
            e.printStackTrace();
        }
    }

    public Connection getConnection()throws SQLException {
        return DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/chatroomaccount?characterEncoding=UTF-8",
                "root",
                "qwe130144"
        );
    }

    public int getTotal(){
        int total = 0;
        try (Connection c = getConnection();
        Statement s = c.createStatement()){
            String sql = "select count(*) from chataccount";
            ResultSet rs = s.executeQuery(sql);
            if(rs.next()){
                total = rs.getInt(1);
            }
        }catch (SQLException e){
            e.printStackTrace();
        }
        return total;
    }

    public void add(UserInfo user){
        String sqlpat = "insert into chataccount values(null,?,?)";
        try (Connection c = getConnection();
        PreparedStatement ps = c.prepareStatement(sqlpat)){
            ps.setString(1,user.getName());
            ps.setString(2,user.getPsw());
            ps.execute();

        }catch (SQLException e){
            e.printStackTrace();
        }
    }

    public UserInfo get(int id){
        UserInfo user = null;
        String sqlpat = "select * from chataccount where id=?";
        try (Connection c = getConnection();
        PreparedStatement ps = c.prepareStatement(sqlpat)){
            ps.setInt(1,id);
            ResultSet rs = ps.executeQuery();
            if(rs.next()){
                user = new UserInfo();
                user.setName(rs.getString(2));
                user.setPassword(rs.getString(3));
            }
        }catch (SQLException e){
            e.printStackTrace();
        }
        return user;
    }

    public int searchName(String name){
        int resultID = 0;
        String sqlpat = "select id from chataccount where NAME=?";
        try (Connection c = getConnection();
        PreparedStatement ps = c.prepareStatement(sqlpat)){
            ps.setString(1,name);
            ResultSet rs = ps.executeQuery();
            if(rs.next()){
                resultID = rs.getInt(1);
            }
        }catch (SQLException E){
            E.printStackTrace();
        }
        return resultID;
    }
}
